package net.opslog.web.client.activities;

import java.util.ArrayList;
import java.util.List;

import net.opslog.web.client.ClientFactory;
import net.opslog.web.client.models.JSOModel;
import net.opslog.web.client.models.LogEntry;
import net.opslog.web.client.places.MainPlace;
import net.opslog.web.client.service.LogDataProvider;
import net.opslog.web.client.service.LogEntriesRequest;
import net.opslog.web.client.service.UserInfoRequest;
import net.opslog.web.client.views.MainView;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class MainActivity extends AbstractActivity implements
		MainView.Presenter {
	private ClientFactory clientFactory;
	private MainView mainView;

	public MainActivity(MainPlace place, ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		mainView = clientFactory.getMainView();
		mainView.setLogFormat(clientFactory.getConfiguration().getProperty(
				"log_format"));

		mainView.setPresenter(this);
		containerWidget.setWidget(mainView.asWidget());
		// LogDataProvider logDataProvider = new LogDataProvider();
		// logDataProvider.setLogOrder(clientFactory.getConfiguration().getProperty("log_order"));
		// mainView.setLogDataProvider(logDataProvider);

		// Get user info
		UserInfoRequest request = new UserInfoRequest();

		request.getUserInfo(new RequestCallback() {

			@Override
			public void onResponseReceived(Request request, Response response) {
				JSONValue jsonResponse = JSONParser.parseStrict(response
						.getText());
				JSOModel data = JSOModel.fromJson(jsonResponse.isObject()
						.get("info").toString());
				mainView.setUserInfo(data.get("email"));
			}

			@Override
			public void onError(Request request, Throwable exception) {
				Window.alert(exception.getMessage());

			}

		});

	}

	@Override
	public void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);

	}

}
